<template>
  <div class="no-background-container">
    <header-component />
    <div style="height: 60px"></div>
    <el-affix :offset="62">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">
            <!-- <el-button :icon="Back" link @click="goToPage('Index')">返回</el-button> -->
            {{ routeName }}
          </div>
        </div>
        <div class="header-query">
          <div>
            <el-button type="primary" @click="((isEditMode = false), (showFormDialog = true))">新增{{ moduleName }}</el-button>
          </div>
          <query-form
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams()"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <qs-table
      :finally-columns="finallyColumns"
      :layout="layout"
      :list="list"
      :list-loading="listLoading"
      :query-form="queryForm"
      :total="total"
      @handle-current-change="handleCurrentChange"
      @handle-delete="handleDelete"
      @handle-details="handleDetails"
      @handle-edit="handleEdit"
      @handle-size-change="handleSizeChange"
      @update:query-form="updateQueryForm"
    />

    <!-- 表单弹窗 -->
    <form-dialog
      v-model="showFormDialog"
      :add-params="addParams"
      :form-data="form"
      :module-name="moduleName"
      :title="isEditMode ? '编辑' : '新增'"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Public from '~/src/api/public/index'
import HeaderComponent from '../components/header.vue'
import type { MeetingRoom } from './config'
import { addParams, moduleApi, moduleName, searchParams, tableColumns } from './config'
// 新增 form 变量
const form = ref<MeetingRoom | {}>({})

// 编辑行数据
const handleEdit = (row: MeetingRoom) => {
  // 将当前行数据赋值给 form
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}

const updateQueryForm = (newQueryForm: any) => {
  queryForm.value = { ...newQueryForm }
}

// 删除行数据
const handleDelete = (id: MeetingRoom) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里可以添加删除逻辑
        await Public.delApi({ url: moduleApi, id })
      } catch (error) {
        console.error('删除失败:', error)
      } finally {
        fetchData()
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const goToPage = (name: string) => {
  router.push({ name })
}

// 是否为编辑模式
const isEditMode = ref(false)

// 获取当前路由对象
const route = useRoute()

// 计算属性，获取路由名称
const routeName = computed(() => route.meta.title || '')

// 路由实例
const router = useRouter()

// 表格数据
const list = ref<MeetingRoom[]>([])

// 加载状态
const listLoading = ref<boolean>(true)

// 分页布局
const layout = ref<string>('total, sizes, prev, pager, next, jumper')

// 总条数
const total = ref<number>(0)

// 选中的行
const selectRows = ref<MeetingRoom[]>([])

// 显示的列
const checkList = ref<string[]>([])
interface QueryForm {
  page: number
  limit: number
  [key: string]: any // 允许其他动态属性
}
// 查询表单
const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
})
onMounted(() => {
  searchParams().forEach((param) => {
    queryForm.value[param.prop] = null
  })
})
// 最终显示的列
const finallyColumns = computed(() => tableColumns.value.filter((item: any) => checkList.value.includes(item.label)))

// 控制表单弹窗显示
const showFormDialog = ref(false)
interface ApiResponse<T> {
  code: number
  result: T
}
const fetchData = async () => {
  listLoading.value = true
  try {
    console.log(queryForm.value)

    const response = await Public.getDetailApi({ url: moduleApi, params: queryForm.value })
    interface ApiResponse<T> {
      code: number
      result: T
    }
    const { code, result } = response as unknown as ApiResponse<{ rows: MeetingRoom[]; count: number }>
    if (code === 0) {
      list.value = result.rows // 正确
      total.value = result.count // 正确
    }
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (value: number) => {
  console.log(`每页 ${value} 条`)
  updatePagination({ page: 1, limit: value })
}

// 当前页改变
const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

// 更新分页信息并重新获取数据
const updatePagination = (params: { page?: number; limit?: number }) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

// 查询数据
const queryData = () => {
  updatePagination({ page: 1 })
}

// 设置选中的行
const setSelectRows = (value: MeetingRoom[]) => {
  selectRows.value = value
}

// 查看详情
const handleDetails = (row: MeetingRoom) => {
  // router.push({
  //   name: 'ContractsDetails',
  //   query: {
  //     id: row.id,
  //     title: row.roomName,
  //   },
  // })
}

// 表单提交处理
const handleFormSubmit = async (formData: MeetingRoom) => {
  console.log('表单提交的数据:', formData)
  console.log('isEditMode', isEditMode.value)
  if (isEditMode.value) {
    await Public.editApi({ url: moduleApi, data: formData })
      .then((res) => {
        console.log(res)
      })
      .catch((error) => {
        console.log(error)
      })
  } else {
    await Public.addApi({ url: moduleApi, data: formData })
      .then((res) => {
        console.log(res)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  // 这里可以添加提交表单数据的逻辑

  fetchData() // 重新获取数据
}

// 组件激活时刷新表格布局并获取数据
onActivated(() => {
  fetchData()
})

// 组件挂载前初始化列显示和获取数据
onBeforeMount(() => {
  initializeColumns()
  fetchData()
})

// 初始化列显示
const initializeColumns = () => {
  tableColumns.value.forEach((item: any) => {
    if (!item.noChecked) checkList.value.push(item.label)
  })
}
</script>

<style scoped>
.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}
</style>
